using Gateway.IQuery;
using Gateway.IQuery.RequestLog;
using Gateway.IQuery.RequestLog.Request;
using Gateway.IQuery.RequestLog.Result;
using Gateway.IRepositories;
using SqlSugar;

namespace Gateway.Query;

/// <summary>
/// 
/// </summary>
public class RequestLogQuery : IRequestLogQuery
{
    private readonly IQueryRepository _repository;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="repository"></param>
    public RequestLogQuery(IQueryRepository repository)
    {
        _repository = repository;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<PageResult<RequestLogDetailResult>> GetPage(RequestLogPageRequest request)
    {
        RefAsync<int> total = 0;
        var data = await _repository.Db.Queryable<RequestLogDetailResult>()
            .Where(x => ((string.IsNullOrWhiteSpace(request.StartTime) ||
                          (SqlFunc.ToDate(x.CreatedTime)) >= DateTime.Parse(request.StartTime)))
                        && ((string.IsNullOrWhiteSpace(request.EndTime) ||
                             (SqlFunc.ToDate(x.CreatedTime)) <= DateTime.Parse(request.EndTime)))
            )
            .OrderByDescending(x=>x.CreatedTime)
            .Select(x=>new RequestLogDetailResult()
            {
                RequestLogId = x.RequestLogId,
                ApiPath = x.ApiPath,
                CreatedBy = x.CreatedBy,
                CreatedTime = x.CreatedTime,
                CreatorName = x.CreatorName,
                // Event = x.Event,
                HttpMethod = x.HttpMethod,
                Ip = x.Ip,
                LogType = x.LogType,
                LogName = x.LogName,
            })
            .ToPageListAsync(request.Page, request.PageSize, total);
        //
        return PageResult<RequestLogDetailResult>.Create(data, total.Value);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<RequestLogDetailResult> GetDetail(string id)
    {
        return await _repository.FindAsync<RequestLogDetailResult>(x => x.RequestLogId.Equals(id));
    }
}